package com.hotec.PROJECT_NAME.component.dtohandler.callbackhandler;

import com.gemcap.framework.common.data.dto.support.DTOCallbackHandlerAdaptor;
import com.google.common.collect.Lists;
import com.hotec.PROJECT_NAME.component.basic.BaseEntity;
import com.hotec.PROJECT_NAME.modules.sys.entity.SysAttachment;
import com.hotec.PROJECT_NAME.modules.sys.service.SysAttachmentService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * 对待转换的实体进行字典项的转换
 */
@Data
@Slf4j
public class DTOCallbackHandlerWithAttachment extends DTOCallbackHandlerAdaptor {


    private ThreadLocal<Map<String, List<SysAttachment>>> attachments = new ThreadLocal<>();

    private SysAttachmentService sysAttachmentService;

    @Override
    public <T> void preHandle(List<T> objectList) {
        List<String> tmp = Lists.newArrayList();

        for (T item : objectList) {
            if (item == null) {
                continue;
            }
            if (item instanceof BaseEntity ) {
                String id = ((BaseEntity) item).getId();
                if (id == null) {
                    continue;
                }
                tmp.add(id);
            }
        }

//        log.info("查询 业务id 包含的附件列表" + JSON.toJSONString(tmp));

        if (CollectionUtils.isEmpty(tmp)) {
            attachments.remove();
            return;
        }

        //保存映射关系
        attachments.set(sysAttachmentService.queryAttachmentListByBusinessIds(tmp));

    }

    @Override
    public void doHandler(Map<String, Object> dtoMap) {
        //不对id为空记录处理
        if (dtoMap.get("id") == null) {
            return;
        }

        if (attachments.get() == null || attachments.get().size() < 1) {
            if (dtoMap.get("sysAttachments") == null || ((dtoMap.get("sysAttachments") instanceof List) && ((List) dtoMap.get("sysAttachments")).size() < 1)) {
                dtoMap.put("sysAttachments", Lists.newArrayList());
            }
            return;
        }
        List<SysAttachment> sysAttachments = attachments.get().get(dtoMap.get("id"));

        dtoMap.put("sysAttachments", sysAttachments);

        //添加附件数量字段
        dtoMap.put("sysAttachments_num", sysAttachments != null ? sysAttachments.size() : 0);
    }

}
